import axios from "axios";
import { createDiscreteApi } from "naive-ui";
import qs from "qs";
import NProgress from "nprogress";
import "nprogress/nprogress.css";
import store from "../../store";
import $bus from "@/utils/bus";
import { logOut } from "@/utils";

const $Message = createDiscreteApi(["message"]).message;
let errMsgTimer = null;
let logOutStatus = false;

//全局进度条的配置
NProgress.configure({
  easing: "ease", // 动画方式
  speed: 1000, // 递增进度条的速度
  showSpinner: false, // 是否显示加载ico
  trickleSpeed: 200, // 自动递增间隔
  minimum: 0.3 // 初始化时的最小百分比
});

const service = axios.create({
  // timeout: 3500 // 请求超时时间
});

service.interceptors.request.use(
  (config) => {
    if (!config.noLoading) NProgress.start();
    if (store.getters.authorization) {
      config.headers["Authorization"] = store.getters.authorization;
    }
    if (["PROFILEPOST", "FILEPOST"].includes(config.method)) {
      config.headers["Content-Type"] = "multipart/form-data";
    }
    if (["ApplicationPOST", "ApplicationPUT", "AppBlobPOST"].includes(config.method)) {
      config.headers["Content-Type"] = "application/json;charset=UTF-8";
    }
    return config;
  },
  (error) => {
    Promise.reject(error);
  }
);

/**
 * * respone拦截
 * */
service.interceptors.response.use(
  response => {
    NProgress.done();
    // console.log("response => ", response);
    if (response && response.data && response.data.code === 10100) {
    // if (response && response.data && response.data.code === 0) {
      if (!logOutStatus) {
        logOutStatus = true;
        $bus.$emit("@components/base/dialog.closeAll");
        $Message.error("Expired, please log in again");
        logOut();
        setTimeout(() => { logOutStatus = false; }, 1000)
        return null;
      }
    }
    return response;
  },
  error => {
    console.log("respone-error ==> ", error);
    // 关闭进度条
    NProgress.done();
    if (!errMsgTimer) {
      errMsgTimer = true
      $Message.error("Failed to connect to the server");
      setTimeout(() => {errMsgTimer = false }, 1500);
    }
  }
);

export default (url = "", data = {}, method = "", config) => {
  // console.log("http:", config);
  switch (method) {
    case "GET":
      return new Promise((resolve, reject) => {
        service.get(url, {
          params: data,
          paramsSerializer: (params) => {
            return qs.stringify(params);
          },
          noLoading: config && config.noLoading
        }, config)
          .then((res) => {
            if (res.data.code == 0) {
              resolve(res.data.data);
            } else if(res.data.code !== 10100) {
              reject(res.data);
            }
          })
          .catch((err) => {
            console.log("err-----", err);
          });
      });
    case "POST":
      return new Promise((resolve, reject) => {
        service.post(
          url,
          qs.stringify(data, {
            arrayFormat: "indices",
            allowDots: true,
            noLoading: config && config.noLoading
          }),
        )
          .then((res) => {
            if (res.data.code == 0) {
              resolve(res.data.data);
            } else if(res.data.code !== 10100) {
              reject(res.data);
            }
          })
          .catch((err) => {
            console.log("err-----", err);
            // reject(err);
          });
      });
    case "ApplicationPOST":
      return new Promise((resolve, reject) => {
        service({
          method: "POST",
          url: url,
          data: data
        })
          .then((res) => {
            if (res.data.code == 0) {
              resolve(res.data.data);
            } else if(res.data.code !== 10100) {
              reject(res.data);
            }
          })
          .catch((err) => {
            reject(err);
          });
      });
    default:
      break;
  }
};
